package seg.tef4.whms.util.nfc;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Parcelable;
import android.provider.Settings;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.util.Stack;

public class NFCUtil {
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;

    public NFCUtil(Activity activity){
        // 初始化NFC适配器
        mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);
        // NFC适配器可以获取时，检查其是否可用。若不可用则跳转到权限设置处
        if (mNfcAdapter != null) {
            if (!mNfcAdapter.isEnabled()) {
                Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
                activity.startActivity(setNfc);
            }
        }
        // PendingIntent初始化
        mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity,
                activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    }

    /**
     * @description 开启NFC的前台调度
     * @param activity
     */
    public void enableForegroundDispatch(Activity activity){
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(activity, mPendingIntent, null, null);

    }

    /**
     * @description 关闭NFC的前台调度
     * @param activity
     */
    public void disableForegroundDispatch(Activity activity){
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(activity);
    }

    /**
     * @description 读NFC卡的ID
     * @param intent
     * @return
     * @throws UnsupportedEncodingException
     */
    public String readNFCId(Intent intent) throws UnsupportedEncodingException {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String id = ByteArrayToHexString(tag.getId());
        Log.i(NFCUtil.class.toString(),id);
        return id;
    }

    /**
     * @description 读NFC卡中的数据
     * @param intent
     * @return
     * @throws UnsupportedEncodingException
     */
    public String readNFCFromTag(Intent intent) throws UnsupportedEncodingException {
        Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        StringBuilder stringBuilder = new StringBuilder();

        if (rawArray != null) {
            for (int i = 0; i < rawArray.length; i++) {
                NdefMessage mNdefMsg = (NdefMessage) rawArray[i];
                for (int j = 0; j < mNdefMsg.getRecords().length; i++) {
                    NdefRecord mNdefRecord = mNdefMsg.getRecords()[j];
                    if (mNdefRecord != null) {
                        String readResult = new String(mNdefRecord.getPayload(), "UTF-8");
                        stringBuilder.append(readResult).append("\r");
                    }
                }
                stringBuilder.append("\n");
            }
        }
        String result = stringBuilder.toString();
        Log.i(NFCUtil.class.toString(),result);
        return result;
    }

    /**
     * 将字节数组转换为字符串
     */
    private String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
        String out = "";
        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    /**
     * 十六进制转10进制
     * @param s
     * @return
     */
    public static int hexToDec(String s) {
        String s1 = s.toUpperCase(); // 全转大写
        char[] chars = s1.toCharArray(); // 转成 char 数组
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < chars.length; i++) {
            stack.push(chars[i]); // 放入栈中，倒序遍历
        }
        int sum = 0;  // 定义总和
        int size = stack.size(); // 要先赋值给 size ，不然 stack.pop() 之后 size 会变
        for (int i = 0; i < size; i++) {
            Character pop = stack.pop();
            if (String.valueOf(pop).matches("[A-F]")) {  // 如果是 A-F
                sum += (Math.pow(16, i) * ((pop - 55))); // A的ASCII码为 65，取偏移量
            } else { // 如果是纯数字
                sum += Math.pow(16, i) * Integer.parseInt(String.valueOf(pop));
            }
        }
        return sum;
    }
}
